Merge jid-rs project

This commit is contained in:
Maxime “pep” Buquet 2019-10-18 14:23:27 +02:00
commit d9d676a0cb
7 changed files with 1352 additions and 0 deletions

2
jid-rs/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target
Cargo.lock

62
jid-rs/.gitlab-ci.yml Normal file
View file

@ -0,0 +1,62 @@
stages:
- build
- test
variables:
FEATURES: ""
RUST_BACKTRACE: "full"
.stable:
image: rust:latest
cache:
key: stable
paths:
- target/
.nightly:
image: rustlang/rust:nightly
cache:
key: nightly
paths:
- target/
.build:
stage: build
script:
- cargo build --verbose --no-default-features --features=$FEATURES
.test:
stage: test
script:
- cargo test --lib --verbose --no-default-features --features=$FEATURES
rust-latest-build:
extends:
- .build
- .stable
rust-nightly-build:
extends:
- .build
- .nightly
rust-latest-test:
extends:
- .test
- .stable
rust-nightly-test:
extends:
- .test
- .nightly
rust-latest-build with features=minidom:
extends: rust-latest-build
variables:
FEATURES: "minidom"
rust-latest-test with features=minidom:
extends: rust-latest-test
variables:
FEATURES: "minidom"

62
jid-rs/CHANGELOG.md Normal file
View file

@ -0,0 +1,62 @@
Version 0.8, released 2019-10-15:
* Updates
- CI: Split jobs, add tests, and caching
* Breaking
- 0.7.1 was actually a breaking release
Version 0.7.2, released 2019-09-13:
* Updates
- Impl Error for JidParseError again, it got removed due to the failure removal but is still wanted.
Version 0.7.1, released 2019-09-06:
* Updates
- Remove failure dependency, to keep compilation times in check
- Impl Display for Jid
Version 0.7.0, released 2019-07-26:
* Breaking
- Update minidom dependency to 0.11
Version 0.6.2, released 2019-07-20:
* Updates
- Implement From<BareJid> and From<FullJid> for Jid
- Add node and domain getters on Jid
Version 0.6.1, released 2019-06-10:
* Updates
- Change the license from LGPLv3 to MPL-2.0.
Version 0.6.0, released 2019-06-10:
* Updates
- Jid is now an enum, with two variants, Bare(BareJid) and Full(FullJid).
- BareJid and FullJid are two specialised variants of a JID.
Version 0.5.3, released 2019-01-16:
* Updates
- Link Mauve bumped the minidom dependency version.
- Use Edition 2018, putting the baseline rustc version to 1.31.
- Run cargo-fmt on the code, to lower the barrier of entry.
Version 0.5.2, released 2018-07-31:
* Updates
- Astro bumped the minidom dependency version.
- Updated the changelog to reflect that 0.5.1 was never actually released.
Version 0.5.1, "released" 2018-03-01:
* Updates
- Link Mauve implemented failure::Fail on JidParseError.
- Link Mauve simplified the code a bit.
Version 0.5.0, released 2018-02-18:
* Updates
- Link Mauve has updated the optional `minidom` dependency.
- Link Mauve has added tests for invalid JIDs, which adds more error cases.
Version 0.4.0, released 2017-12-27:
* Updates
- Maxime Buquet has updated the optional `minidom` dependency.
- The repository has been transferred to xmpp-rs/jid-rs.
Version 0.3.1, released 2017-10-31:
* Additions
- Link Mauve added a minidom::IntoElements implementation on Jid behind the "minidom" feature. ( https://gitlab.com/lumi/jid-rs/merge_requests/9 )

22
jid-rs/Cargo.toml Normal file
View file

@ -0,0 +1,22 @@
[package]
name = "jid"
version = "0.8.0"
authors = [
"lumi <lumi@pew.im>",
"Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>",
"Maxime “pep” Buquet <pep@bouah.net>",
]
description = "A crate which provides a Jid struct for Jabber IDs."
homepage = "https://gitlab.com/xmpp-rs/jid-rs"
repository = "https://gitlab.com/xmpp-rs/jid-rs"
documentation = "https://docs.rs/jid"
readme = "README.md"
keywords = ["xmpp", "jid"]
license = "MPL-2.0"
edition = "2018"
[badges]
gitlab = { repository = "xmpp-rs/jid-rs" }
[dependencies]
minidom = { version = "0.11", optional = true }

373
jid-rs/LICENSE Normal file
View file

@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
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/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

18
jid-rs/README.md Normal file
View file

@ -0,0 +1,18 @@
jid-rs
======
What's this?
------------
A crate which provides a struct Jid for Jabber IDs. It's used in xmpp-rs but other XMPP libraries
can of course use this.
What license is it under?
-------------------------
MPL-2.0 or later, see the `LICENSE` file.
Notes
-----
This library does not yet implement RFC7622.

813
jid-rs/src/lib.rs Normal file
View file

@ -0,0 +1,813 @@
// 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)]
//! Provides a type for Jabber IDs.
//!
//! For usage, check the documentation on the `Jid` struct.
use std::convert::{Into, TryFrom};
use std::error::Error as StdError;
use std::fmt;
use std::str::FromStr;
/// An error that signifies that a `Jid` cannot be parsed from a string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JidParseError {
/// Happens when there is no domain, that is either the string is empty,
/// starts with a /, or contains the @/ sequence.
NoDomain,
/// Happens when there is no resource, that is string contains no /.
NoResource,
/// Happens when the node is empty, that is the string starts with a @.
EmptyNode,
/// Happens when the resource is empty, that is the string ends with a /.
EmptyResource,
}
impl StdError for JidParseError {}
impl fmt::Display for JidParseError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", match self {
JidParseError::NoDomain => "no domain found in this JID",
JidParseError::NoResource => "no resource found in this full JID",
JidParseError::EmptyNode => "nodepart empty despite the presence of a @",
JidParseError::EmptyResource => "resource empty despite the presence of a /",
})
}
}
/// An enum representing a Jabber ID. It can be either a `FullJid` or a `BareJid`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Jid {
/// Bare Jid
Bare(BareJid),
/// Full Jid
Full(FullJid),
}
impl FromStr for Jid {
type Err = JidParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (ns, ds, rs): StringJid = _from_str(s)?;
Ok(match rs {
Some(rs) => Jid::Full(FullJid {
node: ns,
domain: ds,
resource: rs,
}),
None => Jid::Bare(BareJid {
node: ns,
domain: ds,
}),
})
}
}
impl From<Jid> for String {
fn from(jid: Jid) -> String {
match jid {
Jid::Bare(bare) => String::from(bare),
Jid::Full(full) => String::from(full),
}
}
}
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> {
fmt.write_str(String::from(self.clone()).as_ref())
}
}
impl Jid {
/// The node part of the Jabber ID, if it exists, else None.
pub fn node(self) -> Option<String> {
match self {
Jid::Bare(BareJid { node, .. }) | Jid::Full(FullJid { node, .. }) => node,
}
}
/// The domain of the Jabber ID.
pub fn domain(self) -> String {
match self {
Jid::Bare(BareJid { domain, .. }) | Jid::Full(FullJid { domain, .. }) => domain,
}
}
}
impl From<Jid> for BareJid {
fn from(jid: Jid) -> BareJid {
match jid {
Jid::Full(full) => full.into(),
Jid::Bare(bare) => bare,
}
}
}
impl TryFrom<Jid> for FullJid {
type Error = JidParseError;
fn try_from(jid: Jid) -> Result<Self, Self::Error> {
match jid {
Jid::Full(full) => Ok(full),
Jid::Bare(_) => Err(JidParseError::NoResource),
}
}
}
/// A struct representing a full Jabber ID.
///
/// A full Jabber ID is composed of 3 components, of which one is optional:
///
/// - A node/name, `node`, which is the optional part before the @.
/// - A domain, `domain`, which is the mandatory part after the @ but before the /.
/// - A resource, `resource`, which is the 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` enum.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct FullJid {
/// The node part of the Jabber ID, if it exists, else None.
pub node: Option<String>,
/// The domain of the Jabber ID.
pub domain: String,
/// The resource of the Jabber ID.
pub resource: String,
}
/// A struct representing a bare Jabber ID.
///
/// A bare Jabber ID is composed of 2 components, of which one is optional:
///
/// - A node/name, `node`, which is the optional part before the @.
/// - A domain, `domain`, which is the mandatory part after the @.
///
/// Unlike a `FullJid`, it cant 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` enum.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct BareJid {
/// The node part of the Jabber ID, if it exists, else None.
pub node: Option<String>,
/// The domain of the Jabber ID.
pub domain: String,
}
impl From<FullJid> for String {
fn from(jid: FullJid) -> String {
let mut string = String::new();
if let Some(ref node) = jid.node {
string.push_str(node);
string.push('@');
}
string.push_str(&jid.domain);
string.push('/');
string.push_str(&jid.resource);
string
}
}
impl From<BareJid> for String {
fn from(jid: BareJid) -> String {
let mut string = String::new();
if let Some(ref node) = jid.node {
string.push_str(node);
string.push('@');
}
string.push_str(&jid.domain);
string
}
}
impl Into<BareJid> for FullJid {
fn into(self) -> BareJid {
BareJid {
node: self.node,
domain: self.domain,
}
}
}
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(String::from(self.clone()).as_ref())
}
}
impl fmt::Display for BareJid {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt.write_str(String::from(self.clone()).as_ref())
}
}
enum ParserState {
Node,
Domain,
Resource,
}
type StringJid = (Option<String>, String, Option<String>);
fn _from_str(s: &str) -> Result<StringJid, JidParseError> {
// TODO: very naive, may need to do it differently
let iter = s.chars();
let mut buf = String::with_capacity(s.len());
let mut state = ParserState::Node;
let mut node = None;
let mut domain = None;
let mut resource = None;
for c in iter {
match state {
ParserState::Node => {
match c {
'@' => {
if buf == "" {
return Err(JidParseError::EmptyNode);
}
state = ParserState::Domain;
node = Some(buf.clone()); // TODO: performance tweaks, do not need to copy it
buf.clear();
}
'/' => {
if buf == "" {
return Err(JidParseError::NoDomain);
}
state = ParserState::Resource;
domain = Some(buf.clone()); // TODO: performance tweaks
buf.clear();
}
c => {
buf.push(c);
}
}
}
ParserState::Domain => {
match c {
'/' => {
if buf == "" {
return Err(JidParseError::NoDomain);
}
state = ParserState::Resource;
domain = Some(buf.clone()); // TODO: performance tweaks
buf.clear();
}
c => {
buf.push(c);
}
}
}
ParserState::Resource => {
buf.push(c);
}
}
}
if !buf.is_empty() {
match state {
ParserState::Node => {
domain = Some(buf);
}
ParserState::Domain => {
domain = Some(buf);
}
ParserState::Resource => {
resource = Some(buf);
}
}
} else if let ParserState::Resource = state {
return Err(JidParseError::EmptyResource);
}
Ok((node, domain.ok_or(JidParseError::NoDomain)?, resource))
}
impl FromStr for FullJid {
type Err = JidParseError;
fn from_str(s: &str) -> Result<FullJid, JidParseError> {
let (ns, ds, rs): StringJid = _from_str(s)?;
Ok(FullJid {
node: ns,
domain: ds,
resource: rs.ok_or(JidParseError::NoResource)?,
})
}
}
impl FullJid {
/// Constructs a full Jabber ID containing all three components.
///
/// This is of the form `node`@`domain`/`resource`.
///
/// # Examples
///
/// ```
/// use jid::FullJid;
///
/// let jid = FullJid::new("node", "domain", "resource");
///
/// assert_eq!(jid.node, Some("node".to_owned()));
/// assert_eq!(jid.domain, "domain".to_owned());
/// assert_eq!(jid.resource, "resource".to_owned());
/// ```
pub fn new<NS, DS, RS>(node: NS, domain: DS, resource: RS) -> FullJid
where
NS: Into<String>,
DS: Into<String>,
RS: Into<String>,
{
FullJid {
node: Some(node.into()),
domain: domain.into(),
resource: resource.into(),
}
}
/// Constructs a new Jabber ID from an existing one, with the node swapped out with a new one.
///
/// # Examples
///
/// ```
/// use jid::FullJid;
///
/// let jid = FullJid::new("node", "domain", "resource");
///
/// assert_eq!(jid.node, Some("node".to_owned()));
///
/// let new_jid = jid.with_node("new_node");
///
/// assert_eq!(new_jid.node, Some("new_node".to_owned()));
/// ```
pub fn with_node<NS>(&self, node: NS) -> FullJid
where
NS: Into<String>,
{
FullJid {
node: Some(node.into()),
domain: self.domain.clone(),
resource: self.resource.clone(),
}
}
/// Constructs a new Jabber ID from an existing one, with the domain swapped out with a new one.
///
/// # Examples
///
/// ```
/// use jid::FullJid;
///
/// let jid = FullJid::new("node", "domain", "resource");
///
/// assert_eq!(jid.domain, "domain".to_owned());
///
/// let new_jid = jid.with_domain("new_domain");
///
/// assert_eq!(new_jid.domain, "new_domain");
/// ```
pub fn with_domain<DS>(&self, domain: DS) -> FullJid
where
DS: Into<String>,
{
FullJid {
node: self.node.clone(),
domain: domain.into(),
resource: self.resource.clone(),
}
}
/// Constructs a full Jabber ID from a bare Jabber ID, specifying a `resource`.
///
/// # Examples
///
/// ```
/// use jid::FullJid;
///
/// let jid = FullJid::new("node", "domain", "resource");
///
/// assert_eq!(jid.resource, "resource".to_owned());
///
/// let new_jid = jid.with_resource("new_resource");
///
/// assert_eq!(new_jid.resource, "new_resource");
/// ```
pub fn with_resource<RS>(&self, resource: RS) -> FullJid
where
RS: Into<String>,
{
FullJid {
node: self.node.clone(),
domain: self.domain.clone(),
resource: resource.into(),
}
}
}
impl FromStr for BareJid {
type Err = JidParseError;
fn from_str(s: &str) -> Result<BareJid, JidParseError> {
let (ns, ds, _rs): StringJid = _from_str(s)?;
Ok(BareJid {
node: ns,
domain: ds,
})
}
}
impl BareJid {
/// Constructs a bare Jabber ID, containing two components.
///
/// This is of the form `node`@`domain`.
///
/// # Examples
///
/// ```
/// use jid::BareJid;
///
/// let jid = BareJid::new("node", "domain");
///
/// assert_eq!(jid.node, Some("node".to_owned()));
/// assert_eq!(jid.domain, "domain".to_owned());
/// ```
pub fn new<NS, DS>(node: NS, domain: DS) -> BareJid
where
NS: Into<String>,
DS: Into<String>,
{
BareJid {
node: Some(node.into()),
domain: domain.into(),
}
}
/// Constructs a bare Jabber ID containing only a `domain`.
///
/// This is of the form `domain`.
///
/// # Examples
///
/// ```
/// use jid::BareJid;
///
/// let jid = BareJid::domain("domain");
///
/// assert_eq!(jid.node, None);
/// assert_eq!(jid.domain, "domain".to_owned());
/// ```
pub fn domain<DS>(domain: DS) -> BareJid
where
DS: Into<String>,
{
BareJid {
node: None,
domain: domain.into(),
}
}
/// Constructs a new Jabber ID from an existing one, with the node swapped out with a new one.
///
/// # Examples
///
/// ```
/// use jid::BareJid;
///
/// let jid = BareJid::domain("domain");
///
/// assert_eq!(jid.node, None);
///
/// let new_jid = jid.with_node("node");
///
/// assert_eq!(new_jid.node, Some("node".to_owned()));
/// ```
pub fn with_node<NS>(&self, node: NS) -> BareJid
where
NS: Into<String>,
{
BareJid {
node: Some(node.into()),
domain: self.domain.clone(),
}
}
/// Constructs a new Jabber ID from an existing one, with the domain swapped out with a new one.
///
/// # Examples
///
/// ```
/// use jid::BareJid;
///
/// let jid = BareJid::domain("domain");
///
/// assert_eq!(jid.domain, "domain");
///
/// let new_jid = jid.with_domain("new_domain");
///
/// assert_eq!(new_jid.domain, "new_domain");
/// ```
pub fn with_domain<DS>(&self, domain: DS) -> BareJid
where
DS: Into<String>,
{
BareJid {
node: self.node.clone(),
domain: domain.into(),
}
}
/// Constructs a full Jabber ID from a bare Jabber ID, specifying a `resource`.
///
/// # Examples
///
/// ```
/// use jid::BareJid;
///
/// let bare = BareJid::new("node", "domain");
/// let full = bare.with_resource("resource");
///
/// assert_eq!(full.node, Some("node".to_owned()));
/// assert_eq!(full.domain, "domain".to_owned());
/// assert_eq!(full.resource, "resource".to_owned());
/// ```
pub fn with_resource<RS>(self, resource: RS) -> FullJid
where
RS: Into<String>,
{
FullJid {
node: self.node,
domain: self.domain,
resource: resource.into(),
}
}
}
#[cfg(feature = "minidom")]
use minidom::{IntoAttributeValue, Node};
#[cfg(feature = "minidom")]
impl IntoAttributeValue for Jid {
fn into_attribute_value(self) -> Option<String> {
Some(String::from(self))
}
}
#[cfg(feature = "minidom")]
impl Into<Node> for Jid {
fn into(self) -> Node {
Node::Text(String::from(self))
}
}
#[cfg(feature = "minidom")]
impl IntoAttributeValue for FullJid {
fn into_attribute_value(self) -> Option<String> {
Some(String::from(self))
}
}
#[cfg(feature = "minidom")]
impl Into<Node> for FullJid {
fn into(self) -> Node {
Node::Text(String::from(self))
}
}
#[cfg(feature = "minidom")]
impl IntoAttributeValue for BareJid {
fn into_attribute_value(self) -> Option<String> {
Some(String::from(self))
}
}
#[cfg(feature = "minidom")]
impl Into<Node> for BareJid {
fn into(self) -> Node {
Node::Text(String::from(self))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
use std::collections::HashMap;
#[test]
fn can_parse_full_jids() {
assert_eq!(
FullJid::from_str("a@b.c/d"),
Ok(FullJid::new("a", "b.c", "d"))
);
assert_eq!(
FullJid::from_str("b.c/d"),
Ok(FullJid {
node: None,
domain: "b.c".to_owned(),
resource: "d".to_owned(),
})
);
assert_eq!(FullJid::from_str("a@b.c"), Err(JidParseError::NoResource));
assert_eq!(FullJid::from_str("b.c"), Err(JidParseError::NoResource));
}
#[test]
fn can_parse_bare_jids() {
assert_eq!(BareJid::from_str("a@b.c/d"), Ok(BareJid::new("a", "b.c")));
assert_eq!(
BareJid::from_str("b.c/d"),
Ok(BareJid {
node: None,
domain: "b.c".to_owned(),
})
);
assert_eq!(BareJid::from_str("a@b.c"), Ok(BareJid::new("a", "b.c")));
assert_eq!(
BareJid::from_str("b.c"),
Ok(BareJid {
node: None,
domain: "b.c".to_owned(),
})
);
}
#[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").into();
assert_eq!(bare, BareJid::new("a", "b.c"));
}
#[test]
fn bare_to_full_jid() {
assert_eq!(
BareJid::new("a", "b.c").with_resource("d"),
FullJid::new("a", "b.c", "d")
);
}
#[test]
fn node_from_jid() {
assert_eq!(
Jid::Full(FullJid::new("a", "b.c", "d")).node(),
Some(String::from("a")),
);
}
#[test]
fn domain_from_jid() {
assert_eq!(
Jid::Bare(BareJid::new("a", "b.c")).domain(),
String::from("b.c"),
);
}
#[test]
fn jid_to_full_bare() {
let full = FullJid::new("a", "b.c", "d");
let bare = BareJid::new("a", "b.c");
assert_eq!(
FullJid::try_from(Jid::Full(full.clone())),
Ok(full.clone()),
);
assert_eq!(
FullJid::try_from(Jid::Bare(bare.clone())),
Err(JidParseError::NoResource),
);
assert_eq!(
BareJid::from(Jid::Full(full.clone())),
bare.clone(),
);
assert_eq!(
BareJid::from(Jid::Bare(bare.clone())),
bare,
);
}
#[test]
fn serialise() {
assert_eq!(
String::from(FullJid::new("a", "b", "c")),
String::from("a@b/c")
);
assert_eq!(String::from(BareJid::new("a", "b")), String::from("a@b"));
}
#[test]
fn hash() {
let _map: HashMap<Jid, String> = HashMap::new();
}
#[test]
fn invalid_jids() {
assert_eq!(BareJid::from_str(""), Err(JidParseError::NoDomain));
assert_eq!(BareJid::from_str("/c"), Err(JidParseError::NoDomain));
assert_eq!(BareJid::from_str("a@/c"), Err(JidParseError::NoDomain));
assert_eq!(BareJid::from_str("@b"), Err(JidParseError::EmptyNode));
assert_eq!(BareJid::from_str("b/"), Err(JidParseError::EmptyResource));
assert_eq!(FullJid::from_str(""), Err(JidParseError::NoDomain));
assert_eq!(FullJid::from_str("/c"), Err(JidParseError::NoDomain));
assert_eq!(FullJid::from_str("a@/c"), Err(JidParseError::NoDomain));
assert_eq!(FullJid::from_str("@b"), Err(JidParseError::EmptyNode));
assert_eq!(FullJid::from_str("b/"), Err(JidParseError::EmptyResource));
assert_eq!(FullJid::from_str("a@b"), Err(JidParseError::NoResource));
}
#[test]
fn display_jids() {
assert_eq!(format!("{}", FullJid::new("a", "b", "c")), String::from("a@b/c"));
assert_eq!(format!("{}", BareJid::new("a", "b")), String::from("a@b"));
assert_eq!(format!("{}", Jid::Full(FullJid::new("a", "b", "c"))), String::from("a@b/c"));
assert_eq!(format!("{}", Jid::Bare(BareJid::new("a", "b"))), String::from("a@b"));
}
#[cfg(feature = "minidom")]
#[test]
fn minidom() {
let elem: minidom::Element = "<message 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")));
let elem: minidom::Element = "<message from='a@b'/>".parse().unwrap();
let to: Jid = elem.attr("from").unwrap().parse().unwrap();
assert_eq!(to, Jid::Bare(BareJid::new("a", "b")));
let elem: minidom::Element = "<message from='a@b/c'/>".parse().unwrap();
let to: FullJid = elem.attr("from").unwrap().parse().unwrap();
assert_eq!(to, FullJid::new("a", "b", "c"));
let elem: minidom::Element = "<message from='a@b'/>".parse().unwrap();
let to: BareJid = elem.attr("from").unwrap().parse().unwrap();
assert_eq!(to, BareJid::new("a", "b"));
}
#[cfg(feature = "minidom")]
#[test]
fn minidom_into_attr() {
let full = FullJid::new("a", "b", "c");
let elem = minidom::Element::builder("message")
.ns("jabber:client")
.attr("from", full.clone())
.build();
assert_eq!(elem.attr("from"), Some(String::from(full).as_ref()));
let bare = BareJid::new("a", "b");
let elem = minidom::Element::builder("message")
.ns("jabber:client")
.attr("from", bare.clone())
.build();
assert_eq!(elem.attr("from"), Some(String::from(bare.clone()).as_ref()));
let jid = Jid::Bare(bare.clone());
let _elem = minidom::Element::builder("message")
.ns("jabber:client")
.attr("from", jid)
.build();
assert_eq!(elem.attr("from"), Some(String::from(bare).as_ref()));
}
}