Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"29b42712b67b6bf82360d52f576b0eb213babd9e61091a68a62e16463e75005f",".github/workflows/ci.yml":"7b43f41a373147615ff4748d2eaef92dd54ff1f76151a040600774aa59d12187","Cargo.toml":"6793c954abec69ecabe2f88e758729fc5e2835c0a8b668236610cccdcb3a0add","Cargo.toml.orig":"4d108ac2d90a29b453f37eaa6d52ba25f7435be7688aea1da939f501256a3d9e","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"a07450fd4496cb8b58466e6d529f1f502444eee4a235659337e9194d694739d6","README.md":"7ee96ea9abbba189eb19ceed718c0c5114b94ad6df86a7de382d3a74ee1e3c09","src/lib.rs":"54890f714163c81c0681b8d9112db3e7d4b2ccfa085add449fbb413ec10e182a","src/rfc3454.rs":"ba02438db15f665126e5497a464c3e9ff4ea431f1b5b30f0cecde3b02262b5d6","src/tables.rs":"57940490bc844a6db629e4fce0aab99501fad07bac3dc47f17a3905b2c6ea0e1","tests/nameprep_tests.rs":"8ea4f45766b971226caa632c449716c215cfb79587adb5f84654a1c2f6d70a9b","tests/nodeprep_tests.rs":"593c754fec39729120a86348db37907329e763542e26cb30b4d3aae6d8ed77e4","tests/saslprep_tests.rs":"331fda68360157d24838c95f9050fe0f020b853b1543d3b4182252ec8dfe5cf7"},"package":"7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "97e2588933017b48122e8bb574efebb7410fa71c"
},
"path_in_vcs": ""
}
@@ -0,0 +1,76 @@
name: CI
on:
pull_request:
branches:
- master
push:
branches:
- master
env:
RUSTFLAGS: -Dwarnings
RUST_BACKTRACE: 1
jobs:
rustfmt:
name: rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: sfackler/actions/rustup@master
- uses: sfackler/actions/rustfmt@master
clippy:
name: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: sfackler/actions/rustup@master
- run: echo "version=$(rustc --version)" >> $GITHUB_OUTPUT
id: rust-version
- uses: actions/cache@v3
with:
path: ~/.cargo/registry/index
key: index-${{ runner.os }}-${{ github.run_number }}
restore-keys: |
index-${{ runner.os }}-
- run: cargo generate-lockfile
- uses: actions/cache@v3
with:
path: ~/.cargo/registry/cache
key: registry-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }}
- run: cargo fetch
- uses: actions/cache@v3
with:
path: target
key: clippy-target-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }}y
- run: cargo clippy --all --all-targets
test:
name: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: sfackler/actions/rustup@master
with:
version: 1.56.0
- run: echo "version=$(rustc --version)" >> $GITHUB_OUTPUT
id: rust-version
- uses: actions/cache@v3
with:
path: ~/.cargo/registry/index
key: index-${{ runner.os }}-${{ github.run_number }}
restore-keys: |
index-${{ runner.os }}-
- run: cargo generate-lockfile
- uses: actions/cache@v3
with:
path: ~/.cargo/registry/cache
key: registry-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }}
- run: cargo fetch
- uses: actions/cache@v3
with:
path: target
key: test-target-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }}y
- run: cargo test --all
+28
View File
@@ -0,0 +1,28 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
name = "stringprep"
version = "0.1.5"
authors = ["Steven Fackler <sfackler@gmail.com>"]
description = "An implementation of the stringprep algorithm"
readme = "README.md"
license = "MIT/Apache-2.0"
repository = "https://github.com/sfackler/rust-stringprep"
[dependencies.unicode-bidi]
version = "0.3"
[dependencies.unicode-normalization]
version = "0.1"
[dependencies.unicode-properties]
version = "0.1.1"
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "stringprep"
version = "0.1.5"
authors = ["Steven Fackler <sfackler@gmail.com>"]
license = "MIT/Apache-2.0"
description = "An implementation of the stringprep algorithm"
repository = "https://github.com/sfackler/rust-stringprep"
readme = "README.md"
[dependencies]
unicode-bidi = "0.3"
unicode-normalization = "0.1"
unicode-properties = "0.1.1"
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2017 The rust-stringprep Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+23
View File
@@ -0,0 +1,23 @@
# stringprep
[Documentation](https://docs.rs/stringprep)
An implementation of the stringprep algorithm as defined in [RFC 3454][].
[RFC 3454]: https://tools.ietf.org/html/rfc3454
## License
Licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.
+437
View File
@@ -0,0 +1,437 @@
//! An implementation of the "stringprep" algorithm defined in [RFC 3454][].
//!
//! [RFC 3454]: https://tools.ietf.org/html/rfc3454
#![warn(missing_docs)]
extern crate unicode_bidi;
extern crate unicode_normalization;
extern crate unicode_properties;
use std::borrow::Cow;
use std::fmt;
use unicode_normalization::UnicodeNormalization;
use unicode_properties::{GeneralCategoryGroup, UnicodeGeneralCategory};
mod rfc3454;
pub mod tables;
/// Describes why a string failed stringprep normalization.
#[derive(Debug)]
enum ErrorCause {
/// Contains stringprep prohibited characters.
ProhibitedCharacter(char),
/// Violates stringprep rules for bidirectional text.
ProhibitedBidirectionalText,
/// Starts with a combining character
StartsWithCombiningCharacter,
/// Empty String
EmptyString,
}
/// An error performing the stringprep algorithm.
#[derive(Debug)]
pub struct Error(ErrorCause);
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
ErrorCause::ProhibitedCharacter(c) => write!(fmt, "prohibited character `{}`", c),
ErrorCause::ProhibitedBidirectionalText => write!(fmt, "prohibited bidirectional text"),
ErrorCause::StartsWithCombiningCharacter => {
write!(fmt, "starts with combining character")
}
ErrorCause::EmptyString => write!(fmt, "empty string"),
}
}
}
impl std::error::Error for Error {}
/// Prepares a string with the SASLprep profile of the stringprep algorithm.
///
/// SASLprep is defined in [RFC 4013][].
///
/// [RFC 4013]: https://tools.ietf.org/html/rfc4013
pub fn saslprep(s: &str) -> Result<Cow<'_, str>, Error> {
// fast path for ascii text
if s.chars()
.all(|c| c.is_ascii() && !tables::ascii_control_character(c))
{
return Ok(Cow::Borrowed(s));
}
// 2.1 Mapping
let mapped = s
.chars()
.map(|c| {
if tables::non_ascii_space_character(c) {
' '
} else {
c
}
})
.filter(|&c| !tables::commonly_mapped_to_nothing(c));
// 2.2 Normalization
let normalized = mapped.nfkc().collect::<String>();
// 2.3 Prohibited Output
let prohibited = normalized.chars().find(|&c| {
tables::non_ascii_space_character(c) /* C.1.2 */ ||
tables::ascii_control_character(c) /* C.2.1 */ ||
tables::non_ascii_control_character(c) /* C.2.2 */ ||
tables::private_use(c) /* C.3 */ ||
tables::non_character_code_point(c) /* C.4 */ ||
tables::surrogate_code(c) /* C.5 */ ||
tables::inappropriate_for_plain_text(c) /* C.6 */ ||
tables::inappropriate_for_canonical_representation(c) /* C.7 */ ||
tables::change_display_properties_or_deprecated(c) /* C.8 */ ||
tables::tagging_character(c) /* C.9 */
});
if let Some(c) = prohibited {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
// 2.4. Bidirectional Characters
if is_prohibited_bidirectional_text(&normalized) {
return Err(Error(ErrorCause::ProhibitedBidirectionalText));
}
// 2.5 Unassigned Code Points
let unassigned = normalized
.chars()
.find(|&c| tables::unassigned_code_point(c));
if let Some(c) = unassigned {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
Ok(Cow::Owned(normalized))
}
// RFC3454, 6. Bidirectional Characters
fn is_prohibited_bidirectional_text(s: &str) -> bool {
if s.contains(tables::bidi_r_or_al) {
// 2) If a string contains any RandALCat character, the string
// MUST NOT contain any LCat character.
if s.contains(tables::bidi_l) {
return true;
}
// 3) If a string contains any RandALCat character, a RandALCat
// character MUST be the first character of the string, and a
// RandALCat character MUST be the last character of the string.
if !tables::bidi_r_or_al(s.chars().next().unwrap())
|| !tables::bidi_r_or_al(s.chars().next_back().unwrap())
{
return true;
}
}
false
}
/// Prepares a string with the Nameprep profile of the stringprep algorithm.
///
/// Nameprep is defined in [RFC 3491][].
///
/// [RFC 3491]: https://tools.ietf.org/html/rfc3491
pub fn nameprep(s: &str) -> Result<Cow<'_, str>, Error> {
// fast path for ascii text
if s.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '-')
{
return Ok(Cow::Borrowed(s));
}
// 3. Mapping
let mapped = s
.chars()
.filter(|&c| !tables::commonly_mapped_to_nothing(c))
.flat_map(tables::case_fold_for_nfkc);
// 4. Normalization
let normalized = mapped.nfkc().collect::<String>();
// 5. Prohibited Output
let prohibited = normalized.chars().find(|&c| {
tables::non_ascii_space_character(c) /* C.1.2 */ ||
tables::non_ascii_control_character(c) /* C.2.2 */ ||
tables::private_use(c) /* C.3 */ ||
tables::non_character_code_point(c) /* C.4 */ ||
tables::surrogate_code(c) /* C.5 */ ||
tables::inappropriate_for_plain_text(c) /* C.6 */ ||
tables::inappropriate_for_canonical_representation(c) /* C.7 */ ||
tables::change_display_properties_or_deprecated(c) /* C.9 */ ||
tables::tagging_character(c) /* C.9 */
});
if let Some(c) = prohibited {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
// 6. Bidirectional Characters
if is_prohibited_bidirectional_text(&normalized) {
return Err(Error(ErrorCause::ProhibitedBidirectionalText));
}
// 7 Unassigned Code Points
let unassigned = normalized
.chars()
.find(|&c| tables::unassigned_code_point(c));
if let Some(c) = unassigned {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
Ok(Cow::Owned(normalized))
}
/// Prepares a string with the Nodeprep profile of the stringprep algorithm.
///
/// Nameprep is defined in [RFC 3920, Appendix A][].
///
/// [RFC 3920, Appendix A]: https://tools.ietf.org/html/rfc3920#appendix-A
pub fn nodeprep(s: &str) -> Result<Cow<'_, str>, Error> {
// fast path for common ascii text
if s.chars()
.all(|c| matches!(c, '['..='~' | '0'..='9' | '('..='.' | '#'..='%'))
{
return Ok(Cow::Borrowed(s));
}
// A.3. Mapping
let mapped = s
.chars()
.filter(|&c| !tables::commonly_mapped_to_nothing(c))
.flat_map(tables::case_fold_for_nfkc);
// A.4. Normalization
let normalized = mapped.nfkc().collect::<String>();
// A.5. Prohibited Output
let prohibited = normalized.chars().find(|&c| {
tables::ascii_space_character(c) /* C.1.1 */ ||
tables::non_ascii_space_character(c) /* C.1.2 */ ||
tables::ascii_control_character(c) /* C.2.1 */ ||
tables::non_ascii_control_character(c) /* C.2.2 */ ||
tables::private_use(c) /* C.3 */ ||
tables::non_character_code_point(c) /* C.4 */ ||
tables::surrogate_code(c) /* C.5 */ ||
tables::inappropriate_for_plain_text(c) /* C.6 */ ||
tables::inappropriate_for_canonical_representation(c) /* C.7 */ ||
tables::change_display_properties_or_deprecated(c) /* C.9 */ ||
tables::tagging_character(c) /* C.9 */ ||
prohibited_node_character(c)
});
if let Some(c) = prohibited {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
// A.6. Bidirectional Characters
if is_prohibited_bidirectional_text(&normalized) {
return Err(Error(ErrorCause::ProhibitedBidirectionalText));
}
let unassigned = normalized
.chars()
.find(|&c| tables::unassigned_code_point(c));
if let Some(c) = unassigned {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
Ok(Cow::Owned(normalized))
}
// Additional characters not allowed in JID nodes, by RFC3920.
fn prohibited_node_character(c: char) -> bool {
matches!(c, '"' | '&' | '\'' | '/' | ':' | '<' | '>' | '@')
}
/// Prepares a string with the Resourceprep profile of the stringprep algorithm.
///
/// Nameprep is defined in [RFC 3920, Appendix B][].
///
/// [RFC 3920, Appendix B]: https://tools.ietf.org/html/rfc3920#appendix-B
pub fn resourceprep(s: &str) -> Result<Cow<'_, str>, Error> {
// fast path for ascii text
if s.chars().all(|c| matches!(c, ' '..='~')) {
return Ok(Cow::Borrowed(s));
}
// B.3. Mapping
let mapped = s
.chars()
.filter(|&c| !tables::commonly_mapped_to_nothing(c))
.collect::<String>();
// B.4. Normalization
let normalized = mapped.nfkc().collect::<String>();
// B.5. Prohibited Output
let prohibited = normalized.chars().find(|&c| {
tables::non_ascii_space_character(c) /* C.1.2 */ ||
tables::ascii_control_character(c) /* C.2.1 */ ||
tables::non_ascii_control_character(c) /* C.2.2 */ ||
tables::private_use(c) /* C.3 */ ||
tables::non_character_code_point(c) /* C.4 */ ||
tables::surrogate_code(c) /* C.5 */ ||
tables::inappropriate_for_plain_text(c) /* C.6 */ ||
tables::inappropriate_for_canonical_representation(c) /* C.7 */ ||
tables::change_display_properties_or_deprecated(c) /* C.9 */ ||
tables::tagging_character(c) /* C.9 */
});
if let Some(c) = prohibited {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
// B.6. Bidirectional Characters
if is_prohibited_bidirectional_text(&normalized) {
return Err(Error(ErrorCause::ProhibitedBidirectionalText));
}
let unassigned = normalized
.chars()
.find(|&c| tables::unassigned_code_point(c));
if let Some(c) = unassigned {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
Ok(Cow::Owned(normalized))
}
/// Prepares a string according to the procedures described in Section 7 of
/// [ITU-T Recommendation X.520 (2019)](https://www.itu.int/rec/T-REC-X.520-201910-I/en).
///
/// Note that this function does _not_ remove leading, trailing, or inner
/// spaces as described in Section 7.6, because the characters needing removal
/// will vary across the matching rules and ASN.1 syntaxes used.
pub fn x520prep(s: &str, case_fold: bool) -> Result<Cow<'_, str>, Error> {
if s.is_empty() {
return Err(Error(ErrorCause::EmptyString));
}
if s.chars()
.all(|c| matches!(c, ' '..='~') && (!case_fold || c.is_ascii_lowercase()))
{
return Ok(Cow::Borrowed(s));
}
// 1. Transcode
// Already done because &str is enforced to be Unicode.
// 2. Map
let mapped = s
.chars()
.filter(|&c| !tables::x520_mapped_to_nothing(c))
.map(|c| {
if tables::x520_mapped_to_space(c) {
' '
} else {
c
}
});
// 3. Normalize
let normalized = if case_fold {
mapped
.flat_map(tables::case_fold_for_nfkc)
.collect::<String>()
} else {
mapped.nfkc().collect::<String>()
};
// 4. Prohibit
let prohibited = normalized.chars().find(
|&c| {
tables::unassigned_code_point(c)
|| tables::private_use(c)
|| tables::non_character_code_point(c)
|| tables::surrogate_code(c)
|| c == '\u{FFFD}'
}, // REPLACEMENT CHARACTER
);
if let Some(c) = prohibited {
return Err(Error(ErrorCause::ProhibitedCharacter(c)));
}
// From ITU-T Recommendation X.520, Section 7.4:
// "The first code point of a string is prohibited from being a combining character."
match s.chars().next() {
Some(c) => {
if c.general_category_group() == GeneralCategoryGroup::Mark {
return Err(Error(ErrorCause::StartsWithCombiningCharacter));
}
}
None => return Err(Error(ErrorCause::EmptyString)),
}
// 5. Check bidi
// From ITU-T Recommendation X.520, Section 7.4:
// "There are no bidirectional restrictions. The output string is the input string."
// So there is nothing to do for this step.
// 6. Insignificant Character Removal
// Done in calling functions.
Ok(normalized.into())
}
#[cfg(test)]
mod test {
use super::*;
fn assert_prohibited_character<T>(result: Result<T, Error>) {
match result {
Err(Error(ErrorCause::ProhibitedCharacter(_))) => (),
_ => panic!(),
}
}
fn assert_starts_with_combining_char<T>(result: Result<T, Error>) {
match result {
Err(Error(ErrorCause::StartsWithCombiningCharacter)) => (),
_ => panic!(),
}
}
// RFC4013, 3. Examples
#[test]
fn saslprep_examples() {
assert_prohibited_character(saslprep("\u{0007}"));
}
#[test]
fn nodeprep_examples() {
assert_prohibited_character(nodeprep(" "));
assert_prohibited_character(nodeprep("\u{00a0}"));
assert_prohibited_character(nodeprep("foo@bar"));
}
#[test]
fn resourceprep_examples() {
assert_eq!("foo@bar", resourceprep("foo@bar").unwrap());
}
#[test]
fn x520prep_examples() {
assert_eq!(x520prep("foo@bar", true).unwrap(), "foo@bar");
assert_eq!(
x520prep("J.\u{FE00} \u{9}W. \u{B}wuz h\u{0115}re", false).unwrap(),
"J. W. wuz h\u{0115}re"
);
assert_eq!(
x520prep("J.\u{FE00} \u{9}W. \u{B}wuz h\u{0115}re", true).unwrap(),
"j. w. wuz h\u{0115}re"
);
assert_eq!(x520prep("UPPERCASED", true).unwrap(), "uppercased");
assert_starts_with_combining_char(x520prep("\u{0306}hello", true));
}
#[test]
fn ascii_optimisations() {
if let Cow::Owned(_) = nodeprep("nodepart").unwrap() {
panic!("“nodepart” should get optimised as ASCII");
}
if let Cow::Owned(_) = nameprep("domainpart.example").unwrap() {
panic!("“domainpart.example” should get optimised as ASCII");
}
if let Cow::Owned(_) = resourceprep("resourcepart").unwrap() {
panic!("“resourcepart” should get optimised as ASCII");
}
}
}
File diff suppressed because it is too large Load Diff
+251
View File
@@ -0,0 +1,251 @@
//! Character Tables
use std::cmp::Ordering;
use std::str::Chars;
use unicode_bidi::{bidi_class, BidiClass};
use unicode_properties::{GeneralCategoryGroup, UnicodeGeneralCategory};
use super::rfc3454;
/// A.1 Unassigned code points in Unicode 3.2
pub fn unassigned_code_point(c: char) -> bool {
rfc3454::A_1
.binary_search_by(|&(start, end)| {
if start > c {
Ordering::Greater
} else if end < c {
Ordering::Less
} else {
Ordering::Equal
}
})
.is_ok()
}
/// B.1 Commonly mapped to nothing
pub fn commonly_mapped_to_nothing(c: char) -> bool {
matches!(
c,
'\u{00AD}'
| '\u{034F}'
| '\u{1806}'
| '\u{180B}'
| '\u{180C}'
| '\u{180D}'
| '\u{200B}'
| '\u{200C}'
| '\u{200D}'
| '\u{2060}'
| '\u{FE00}'
| '\u{FE01}'
| '\u{FE02}'
| '\u{FE03}'
| '\u{FE04}'
| '\u{FE05}'
| '\u{FE06}'
| '\u{FE07}'
| '\u{FE08}'
| '\u{FE09}'
| '\u{FE0A}'
| '\u{FE0B}'
| '\u{FE0C}'
| '\u{FE0D}'
| '\u{FE0E}'
| '\u{FE0F}'
| '\u{FEFF}'
)
}
/// B.2 Mapping for case-folding used with NFKC.
pub fn case_fold_for_nfkc(c: char) -> CaseFoldForNfkc {
let inner = match rfc3454::B_2.binary_search_by_key(&c, |e| e.0) {
Ok(idx) => FoldInner::Chars(rfc3454::B_2[idx].1.chars()),
Err(_) => FoldInner::Char(Some(c)),
};
CaseFoldForNfkc(inner)
}
enum FoldInner {
Chars(Chars<'static>),
Char(Option<char>),
}
/// The iterator returned by `case_fold_for_nfkc`.
pub struct CaseFoldForNfkc(FoldInner);
impl Iterator for CaseFoldForNfkc {
type Item = char;
fn next(&mut self) -> Option<char> {
match self.0 {
FoldInner::Chars(ref mut it) => it.next(),
FoldInner::Char(ref mut ch) => ch.take(),
}
}
}
/// C.1.1 ASCII space characters
pub fn ascii_space_character(c: char) -> bool {
c == ' '
}
/// C.1.2 Non-ASCII space characters
pub fn non_ascii_space_character(c: char) -> bool {
matches!(
c,
'\u{00A0}'
| '\u{1680}'
| '\u{2000}'
| '\u{2001}'
| '\u{2002}'
| '\u{2003}'
| '\u{2004}'
| '\u{2005}'
| '\u{2006}'
| '\u{2007}'
| '\u{2008}'
| '\u{2009}'
| '\u{200A}'
| '\u{200B}'
| '\u{202F}'
| '\u{205F}'
| '\u{3000}'
)
}
/// C.2.1 ASCII control characters
pub fn ascii_control_character(c: char) -> bool {
matches!(c, '\u{0000}'..='\u{001F}' | '\u{007F}')
}
/// C.2.2 Non-ASCII control characters
pub fn non_ascii_control_character(c: char) -> bool {
matches!(c, '\u{0080}'..='\u{009F}'
| '\u{06DD}'
| '\u{070F}'
| '\u{180E}'
| '\u{200C}'
| '\u{200D}'
| '\u{2028}'
| '\u{2029}'
| '\u{2060}'
| '\u{2061}'
| '\u{2062}'
| '\u{2063}'
| '\u{206A}'..='\u{206F}'
| '\u{FEFF}'
| '\u{FFF9}'..='\u{FFFC}'
| '\u{1D173}'..='\u{1D17A}')
}
/// C.3 Private use
pub fn private_use(c: char) -> bool {
matches!(c, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}')
}
/// C.4 Non-character code points
pub fn non_character_code_point(c: char) -> bool {
matches!(c, '\u{FDD0}'..='\u{FDEF}'
| '\u{FFFE}'..='\u{FFFF}'
| '\u{1FFFE}'..='\u{1FFFF}'
| '\u{2FFFE}'..='\u{2FFFF}'
| '\u{3FFFE}'..='\u{3FFFF}'
| '\u{4FFFE}'..='\u{4FFFF}'
| '\u{5FFFE}'..='\u{5FFFF}'
| '\u{6FFFE}'..='\u{6FFFF}'
| '\u{7FFFE}'..='\u{7FFFF}'
| '\u{8FFFE}'..='\u{8FFFF}'
| '\u{9FFFE}'..='\u{9FFFF}'
| '\u{AFFFE}'..='\u{AFFFF}'
| '\u{BFFFE}'..='\u{BFFFF}'
| '\u{CFFFE}'..='\u{CFFFF}'
| '\u{DFFFE}'..='\u{DFFFF}'
| '\u{EFFFE}'..='\u{EFFFF}'
| '\u{FFFFE}'..='\u{FFFFF}'
| '\u{10FFFE}'..='\u{10FFFF}')
}
/// C.5 Surrogate codes
#[allow(clippy::match_single_binding)]
pub fn surrogate_code(c: char) -> bool {
match c {
// forbidden by rust
/*'\u{D800}'..='\u{DFFF}' => true,*/
_ => false,
}
}
/// C.6 Inappropriate for plain text
pub fn inappropriate_for_plain_text(c: char) -> bool {
matches!(
c,
'\u{FFF9}' | '\u{FFFA}' | '\u{FFFB}' | '\u{FFFC}' | '\u{FFFD}'
)
}
/// C.7 Inappropriate for canonical representation
pub fn inappropriate_for_canonical_representation(c: char) -> bool {
matches!(c, '\u{2FF0}'..='\u{2FFB}')
}
/// C.8 Change display properties or are deprecated
pub fn change_display_properties_or_deprecated(c: char) -> bool {
matches!(
c,
'\u{0340}'
| '\u{0341}'
| '\u{200E}'
| '\u{200F}'
| '\u{202A}'
| '\u{202B}'
| '\u{202C}'
| '\u{202D}'
| '\u{202E}'
| '\u{206A}'
| '\u{206B}'
| '\u{206C}'
| '\u{206D}'
| '\u{206E}'
| '\u{206F}'
)
}
/// C.9 Tagging characters
pub fn tagging_character(c: char) -> bool {
matches!(c, '\u{E0001}' | '\u{E0020}'..='\u{E007F}')
}
/// D.1 Characters with bidirectional property "R" or "AL"
pub fn bidi_r_or_al(c: char) -> bool {
matches!(bidi_class(c), BidiClass::R | BidiClass::AL)
}
/// D.2 Characters with bidirectional property "L"
pub fn bidi_l(c: char) -> bool {
matches!(bidi_class(c), BidiClass::L)
}
/// Determines if `c` is to be removed according to section 7.2 of
/// [ITU-T Recommendation X.520 (2019)](https://www.itu.int/rec/T-REC-X.520-201910-I/en).
pub fn x520_mapped_to_nothing(c: char) -> bool {
match c {
'\u{00AD}'
| '\u{1806}'
| '\u{034F}'
| '\u{180B}'..='\u{180D}'
| '\u{FE00}'..='\u{FE0F}'
| '\u{FFFC}'
| '\u{200B}' => true,
// Technically control characters, but mapped to whitespace in X.520.
'\u{09}' | '\u{0A}'..='\u{0D}' | '\u{85}' => false,
_ => c.is_control(),
}
}
/// Determines if `c` is to be replaced by SPACE (0x20) according to section 7.2 of
/// [ITU-T Recommendation X.520 (2019)](https://www.itu.int/rec/T-REC-X.520-201910-I/en).
pub fn x520_mapped_to_space(c: char) -> bool {
match c {
'\u{09}' | '\u{0A}'..='\u{0D}' | '\u{85}' => true,
_ => c.general_category_group() == GeneralCategoryGroup::Separator,
}
}
+315
View File
@@ -0,0 +1,315 @@
// Integration tests from https://tools.ietf.org/html/draft-josefsson-idn-test-vectors-00
extern crate stringprep;
use stringprep::{nameprep, Error};
fn assert_prohibited_character<T>(result: Result<T, Error>) {
assert!(result.is_err());
}
fn assert_prohibited_bidirectional_text<T>(result: Result<T, Error>) {
assert!(result.is_err());
}
// Additional examples from http://josefsson.org/idn.php
#[test]
fn test_nameprep() {
assert_eq!(
"安室奈美恵-with-super-monkeys",
nameprep("安室奈美恵-with-SUPER-MONKEYS").unwrap()
);
assert_eq!("미술", nameprep("미술").unwrap()); // Korean
assert_eq!("ليهمابتكلموشعربي؟", nameprep("ليهمابتكلموشعربي؟").unwrap()); // Egyptian
assert_eq!(
"他们为什么不说中文",
nameprep("他们为什么不说中文").unwrap()
); // Chinese
assert_eq!(
"למההםפשוטלאמדבריםעברית",
nameprep("למההםפשוטלאמדבריםעברית").unwrap()
); // Hebrew
assert_eq!(
"почемужеонинеговорятпорусски",
nameprep("почемужеонинеговорятпорусски").unwrap()
); // Russian
assert_eq!(
"tạisaohọkhôngthểchỉnóitiếngviệt",
nameprep("TạisaohọkhôngthểchỉnóitiếngViệt").unwrap()
); // Vietnamese
assert_eq!("ひとつ屋根の下2", nameprep("ひとつ屋根の下2").unwrap()); // Japanese
assert_eq!(
"pročprostěnemluvíčesky",
nameprep("Pročprostěnemluvíčesky").unwrap()
); // Czech
assert_eq!(
"यहलोगहिन्दीक्योंनहींबोलसकतेहैं",
nameprep("यहलोगहिन्दीक्योंनहींबोलसकतेहैं").unwrap()
); // Hindi
assert_eq!("ພາສາລາວ", nameprep("ພາສາລາວ").unwrap()); // Lao
assert_eq!("bonġusaħħa", nameprep("bonġusaħħa").unwrap()); // Maltese
assert_eq!("ελληνικά", nameprep("ελληνικά").unwrap()); // Greek
}
// 4.1 Map to nothing
#[test]
fn should_map_to_nothing() {
let input =
"foo\u{00ad}\u{034f}\u{1806}\u{180b}bar\u{200b}\u{2060}baz\u{fe00}\u{fe08}\u{fe0f}\u{feff}";
assert_eq!("foobarbaz", nameprep(input).unwrap());
}
// 4.2 Case folding ASCII U+0043 U+0041 U+0046 U+0045
#[test]
fn should_case_fold_ascii() {
assert_eq!("cafe", nameprep("CAFE").unwrap());
}
// 4.3 Case folding 8bit U+00DF (german sharp s)
#[test]
fn should_case_fold_8bit() {
assert_eq!("ss", nameprep("\u{00df}").unwrap());
}
// 4.4 Case folding U+0130 (turkish capital I with dot)
#[test]
fn should_case_fold_16bit() {
assert_eq!("\u{0069}\u{0307}", nameprep("\u{0130}").unwrap());
}
// 4.5 Case folding multibyte U+0143 U+037A
#[test]
fn should_case_fold_multibyte() {
let input = "\u{0143}\u{037a}";
let output = "\u{0144} \u{03b9}";
assert_eq!(output, nameprep(input).unwrap());
}
// 4.6 Case folding U+2121 U+33C6 U+1D7BB
#[test]
fn should_case_fold() {
let input = "\u{2121}\u{33c6}\u{1d7bb}";
let output = "telc\u{2215}\u{006b}\u{0067}\u{03c3}";
assert_eq!(output, nameprep(input).unwrap());
}
// 4.7 Normalization of U+006a U+030c U+00A0 U+00AA
#[test]
fn should_normalize() {
let input = "j\u{030c}\u{00a0}\u{00aa}";
let output = "\u{01f0} a";
assert_eq!(output, nameprep(input).unwrap());
}
// 4.8 Case folding U+1FB7 and normalization
#[test]
fn should_case_fold_and_normalize() {
let input = "\u{1fb7}";
let output = "\u{1fb6}\u{03b9}";
assert_eq!(output, nameprep(input).unwrap());
}
// 4.9 Self-reverting case folding U+01F0 and normalization
// 4.10 Self-reverting case folding U+0390 and normalization
// 4.11 Self-reverting case folding U+03B0 and normalization
// 4.12 Self-reverting case folding U+1E96 and normalization
// 4.13 Self-reverting case folding U+1F56 and normalization
#[test]
fn should_revert_case_fold_and_normalization() {
let inputs = ["\u{01f0}", "\u{0390}", "\u{03b0}", "\u{1e96}", "\u{1f56}"];
for input in inputs.iter() {
assert_eq!(*input, nameprep(input).unwrap());
}
}
// 4.14 ASCII space character U+0020
#[test]
fn should_permit_ascii_space() {
assert_eq!(" ", nameprep(" ").unwrap());
}
// 4.15 Non-ASCII 8bit space character U+00A0
#[test]
fn should_map_8bit_space() {
assert_eq!(" ", nameprep("\u{00a0}").unwrap());
}
// 4.16 Non-ASCII multibyte space character U+1680
#[test]
fn should_prohibit_multibyte_space() {
assert_prohibited_character(nameprep("\u{1680}"));
}
// 4.17 Non-ASCII multibyte space character U+2000
#[test]
fn should_map_multibyte_space1() {
assert_eq!(" ", nameprep("\u{2000}").unwrap());
}
// 4.18 Zero Width Space U+200b
#[test]
fn should_drop_zero_width_space() {
assert_eq!("", nameprep("\u{200b}").unwrap());
}
// 4.19 Non-ASCII multibyte space character U+3000
#[test]
fn should_map_multibyte_space2() {
assert_eq!(" ", nameprep("\u{3000}").unwrap());
}
// 4.20 ASCII control characters U+0010 U+007F
#[test]
fn should_permit_ascii_control() {
assert_eq!("\u{0010}\u{007f}", nameprep("\u{0010}\u{007f}").unwrap());
}
// 4.21 Non-ASCII 8bit control character U+0085
#[test]
fn should_prohibit_8bit_control() {
assert_prohibited_character(nameprep("\u{0085}"));
}
// 4.22 Non-ASCII multibyte control character U+180E
#[test]
fn should_prohibit_multibyte_control() {
assert_prohibited_character(nameprep("\u{180e}"));
}
// 4.23 Zero Width No-Break Space U+FEFF
#[test]
fn should_drop_zero_width_no_break_space() {
assert_eq!("", nameprep("\u{feff}").unwrap());
}
// 4.24 Non-ASCII control character U+1D175
#[test]
fn should_prohibit_non_ascii_control() {
assert_prohibited_character(nameprep("\u{1d175}"));
}
// 4.25 Plane 0 private use character U+F123
#[test]
fn should_prohibit_plane0_private_use() {
assert_prohibited_character(nameprep("\u{f123}"));
}
// 4.26 Plane 15 private use character U+F1234
#[test]
fn should_prohibit_plane15_private_use() {
assert_prohibited_character(nameprep("\u{f1234}"));
}
// 4.27 Plane 16 private use character U+10F234
#[test]
fn should_prohibit_plane16_private_use() {
assert_prohibited_character(nameprep("\u{10f234}"));
}
// 4.28 Non-character code point U+8FFFE
#[test]
fn should_prohibit_non_character1() {
assert_prohibited_character(nameprep("\u{8fffe}"));
}
// 4.29 Non-character code point U+10FFFF
#[test]
fn should_prohibit_non_character2() {
assert_prohibited_character(nameprep("\u{10ffff}"));
}
// 4.31 Non-plain text character U+FFFD
#[test]
fn should_prohibit_non_plain_text() {
assert_prohibited_character(nameprep("\u{fffd}"));
}
// 4.32 Ideographic description character U+2FF5
#[test]
fn should_prohibit_ideographic_description() {
assert_prohibited_character(nameprep("\u{2ff5}"));
}
// 4.33 Display property character U+0341
#[test]
fn should_normalize_display_property() {
assert_eq!("\u{0301}", nameprep("\u{0341}").unwrap());
}
// 4.34 Left-to-right mark U+200E
#[test]
fn should_prohibit_left_to_right_mark() {
assert_prohibited_character(nameprep("\u{200e}"));
}
// 4.35 Deprecated U+202A
#[test]
fn should_prohibit_deprecated() {
assert_prohibited_character(nameprep("\u{202a}"));
}
// 4.36 Language tagging character U+E0001
#[test]
fn should_prohibit_language_tagging1() {
assert_prohibited_character(nameprep("\u{e0001}"));
}
// 4.37 Language tagging character U+E0042
#[test]
fn should_prohibit_language_tagging2() {
assert_prohibited_character(nameprep("\u{e0042}"));
}
// 4.38 Bidi: RandALCat character U+05BE and LCat characters
#[test]
fn should_prohibit_randalcat_with_lcat1() {
assert_prohibited_bidirectional_text(nameprep("foo\u{05be}bar"));
}
// 4.39 Bidi: RandALCat character U+FD50 and LCat characters
#[test]
fn should_prohibit_randalcat_with_lcat2() {
assert_prohibited_bidirectional_text(nameprep("foo\u{fd50}bar"));
}
// 4.40 Bidi: RandALCat character U+FB38 and LCat characters
#[test]
fn should_permit_randalcat1() {
assert_eq!("foo \u{064e}bar", nameprep("foo\u{fe76}bar").unwrap());
}
// 4.41 Bidi: RandALCat without trailing RandALCat U+0627 U+0031
#[test]
fn should_prohibit_mixed_randalcat() {
assert_prohibited_bidirectional_text(nameprep("\u{0672}\u{0031}"));
}
// 4.42 Bidi: RandALCat character U+0627 U+0031 U+0628
#[test]
fn should_permit_randalcat2() {
assert_eq!(
"\u{0627}\u{0031}\u{0628}",
nameprep("\u{0627}\u{0031}\u{0628}").unwrap()
);
}
// 4.43 Unassigned code point U+E0002
#[test]
fn should_prohibit_unassigned_code_point() {
assert_prohibited_character(nameprep("\u{e0002}"));
}
// 4.44 Larger test (shrinking)
#[test]
fn should_shrink() {
let input = "X\u{00ad}\u{00df}\u{0130}\u{2121}j\u{030c}\u{00a0}\u{00aa}\u{03b0}\u{2000}";
let output = "xssi\u{0307}tel\u{01f0} a\u{03b0}\u{0020}";
assert_eq!(output, nameprep(input).unwrap());
}
// 4.45 Larger test (expanding)
#[test]
fn should_expand() {
let input = "X\u{00df}\u{3316}\u{0130}\u{2121}\u{249f}\u{3300}";
let output = "xss\u{30ad}\u{30ed}\u{30e1}\u{30fc}\u{30c8}\u{30eb}\u{0069}\u{0307}\u{0074}\u{0065}\u{006c}\u{0028}\u{0064}\u{0029}\u{30a2}\u{30d1}\u{30fc}\u{30c8}";
assert_eq!(output, nameprep(input).unwrap());
}
+12
View File
@@ -0,0 +1,12 @@
// Examples from http://josefsson.org/idn.php
extern crate stringprep;
use stringprep::nodeprep;
#[test]
fn test_nodeprep() {
assert_eq!(
"räksmörgås.josefsson.org",
nodeprep("räksmörgås.josefßon.org").unwrap()
);
}
+82
View File
@@ -0,0 +1,82 @@
// Integration tests from https://github.com/reklatsmasters/saslprep (MIT License)
extern crate stringprep;
use stringprep::{saslprep, Error};
fn assert_prohibited_character<T>(result: Result<T, Error>) {
assert!(result.is_err());
}
fn assert_prohibited_bidirectional_text<T>(result: Result<T, Error>) {
assert!(result.is_err());
}
#[test]
fn should_work_with_latin_letters() {
assert_eq!(saslprep("user").unwrap(), "user");
}
#[test]
fn should_preserve_case() {
assert_eq!(saslprep("USER").unwrap(), "USER");
}
#[test]
fn should_remove_mapped_to_nothing() {
assert_eq!(saslprep("I\u{00AD}X").unwrap(), "IX");
}
#[test]
fn should_replace_non_ascii_space() {
assert_eq!(saslprep("a\u{00A0}b").unwrap(), "a\u{0020}b");
}
#[test]
fn should_normalize_as_nfkc() {
assert_eq!(saslprep("\u{00AA}").unwrap(), "a");
assert_eq!(saslprep("\u{2168}").unwrap(), "IX");
}
#[test]
fn should_not_allow_prohibited_characters() {
// C.2.1 ASCII control characters
assert_prohibited_character(saslprep("a\u{007F}b"));
// C.2.2 Non-ASCII control characters
assert_prohibited_character(saslprep("a\u{06DD}b"));
// C.3 Private use
assert_prohibited_character(saslprep("a\u{E000}b"));
// C.4 Non-character code points
assert_prohibited_character(saslprep("a\u{1FFFE}b"));
// C.5 Surrogate codes
// forbidden by rust
// C.6 Inappropriate for plain text
assert_prohibited_character(saslprep("a\u{FFF9}b"));
// C.7 Inappropriate for canonical representation
assert_prohibited_character(saslprep("a\u{2FF0}b"));
// C.8 Change display properties or are deprecated
assert_prohibited_character(saslprep("a\u{200E}b"));
// C.9 Tagging characters
assert_prohibited_character(saslprep("a\u{E0001}b"));
}
#[test]
fn randalcat_should_be_first_and_last() {
assert_eq!(
saslprep("\u{0627}\u{0031}\u{0628}").unwrap(),
"\u{0627}\u{0031}\u{0628}"
);
assert_prohibited_bidirectional_text(saslprep("\u{0627}\u{0031}"));
}
#[test]
fn should_handle_unassigned_code_points() {
assert_prohibited_character(saslprep("a\u{0487}"));
}